/**
 * 
 */
package server;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.Vector;

/**
 * @author Fleischhacker
 * Thread which Checks Auctions and Notify's
 *
 */
public class NotifyService extends Thread {
	
	private Collection<ServerThread> threads;
	private AuctionManager auctions;
	private UserManager users;
	private int intervall;
	private boolean alive;
	
	public NotifyService(Collection<ServerThread> _threads, AuctionManager _auctions,	UserManager _users, int _intervall) {
		this.threads = _threads;
		this.auctions = _auctions;
		this.users = _users;
		this.intervall = _intervall;
		this.alive = false;
	}

	public void run(){
		this.alive = true;
		System.out.println("= NotifyService started!");
		while(alive){
			try {
				Thread.sleep(intervall);
				Date now = new Date();
				for(Auction a : auctions.listAuctions()){//Checks for outdated Auctions
					if(a.checkAuctionEnded(now)){//Auction ended - notify user
						System.out.println("Auction '"+a.getDescription()+"' ended!.");
						User winner = null;
						if((winner = a.getCurrentTopBidder()) != null){
							winner.addNotification("!auction-ended "+winner.getScreenname()+" "+a.getBidString()+" "+a.getDescription());
							for(User loser : a.getBidderList()){
								if(!loser.equals(winner) && !loser.equals(a.getOwner()))
									loser.addNotification("!auction-ended "+winner.getScreenname()+" "+a.getBidString()+" "+a.getDescription());
							}
							a.getOwner().addNotification("!auction-ended "+winner.getScreenname()+" "+a.getBidString()+" "+a.getDescription());
						}
					}
				}
				for(User u : users.listUsers()){
					while(u.hasNotifications()){ //checks for notifications
						if(u.isOnline()){ //User is Online: grab Thread and send the message!
							for(ServerThread send : threads){
								if(send.isActive()){
									if(send.getUserReference()!= null && send.getUserReference().equals(u)){//Found!
										send.sendNotification();
										break;
									}
								}
							}
						}//else user is offline, can't do much about this
					}
				}
			} catch (InterruptedException e) {System.out.println("ERROR @NotifyService.run():"+e.getMessage());/*e.printStackTrace();*/}
			catch(IOException ioe){System.out.println("ERROR @NotifyService.run():"+ioe.getMessage()); }
		}
		//this.alive = false;	
	}
	
	public void shutdown(){
		this.alive = false;
		System.out.println("NOTIFY-Service: Shutdown");
	}

}
